package com.sopt.friends;

import java.util.ArrayList;

import com.sopt.friends.db.FriendsDBHelper;
import com.sopt.friends.db.Constants.FriendsDB;
import com.sopt.friends.sub.SubGroup;
import com.sopt.friends.util.FriendsContactsManager;
import com.sopt.friends.util.FriendsGroupManager;
import com.sopt.friends.vo.FriendsCommonItem;
import com.sopt.view.HomeMenuAdapter;
import com.sopt.view.HomeMenuEditAdapter;

import android.R.bool;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class GroupActivity extends ActivityGroup {
	private AlertDialog mAlertDialog;
	private ListView ListView01;
	private FriendsGroupManager manager;
	private ArrayList<FriendsCommonItem> menuList;
	LocalActivityManager activityManager;
	private EditText groupNameEditText;
	private boolean isEditMode = false;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group);

		Button backBtn = (Button) findViewById(R.id.backButton);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		Button addBtn = (Button) findViewById(R.id.addButton);
		addBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showGroupCreateDialog();
			}
		});
		
		Button editBtn = (Button) findViewById(R.id.editButton);
		editBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isEditMode){
					groupActivityChangeToEdit();
					isEditMode = true;
				}else{
					initilizeHelpers();
					isEditMode = false;
				}
			}
		});
		
	}
	protected void groupActivityChangeToEdit() {
		
		showToastLong(getResources().getString(R.string.explainGroupEditMode));
		
		menuList = getGroupList();

		ListView01 = (ListView) findViewById(R.id.listFirst);
		HomeMenuEditAdapter infomenuAdapter = new HomeMenuEditAdapter(this,
				R.layout.row_homemenu_layout, menuList);
		
		ListView01.setAdapter(infomenuAdapter);
		
		ListView01.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				FriendsCommonItem curItem = menuList.get(position);
				if(position>0)
					confirmDelete(curItem.getTitle());
				return false;
			}
		});
		
		ListView01.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				FriendsCommonItem curItem = menuList.get(position);
				
				editGroupName(curItem.get_id(), curItem.getTitle());
			}
		});
	}
	private String currentTitle;
	protected void editGroupName(String getId, String title) {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View layout = inflater.inflate(R.layout.dialog_edit, null);
		TextView groupNameInput = (TextView)layout.findViewById(R.id.dialogInput);
		groupNameInput.setText(title);
		currentTitle = title;
		mAlertDialog = new AlertDialog.Builder(this).setTitle(
				getResources().getString(R.string.titleDialogEditGroup))
				.setView(layout).setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								EditText input = (EditText) layout
										.findViewById(R.id.dialogInput);
								groupNameEditText = input;
								if(!isExistGroupName(input.getText().toString())){
									showupdatedGroupName(input.getText().toString());
								}else{
									showToast(getResources().getString(R.string.toastExistGroupName));
								}
							}
						}).setNegativeButton("CANCEL",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								mAlertDialog.cancel();
							}
						}).create();
		mAlertDialog.show();
	}
	
	protected void showGroupCreateDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View layout = inflater.inflate(R.layout.dialog_add, null);
			mAlertDialog = new AlertDialog.Builder(this).setTitle(
				getResources().getString(R.string.titleDialogCreateGroup))
				.setView(layout).setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								EditText input = (EditText) layout
										.findViewById(R.id.dialogInput);
								groupNameEditText = input;
								if(!isExistGroupName(input.getText().toString())){
									showsavedGroupName();
								}else{
									showToast(getResources().getString(R.string.toastExistGroupName));
								}
							}
						}).setNegativeButton("CANCEL",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								mAlertDialog.cancel();
							}
						}).create();
		mAlertDialog.show();
	}

	protected void showsavedGroupName() {
		String inputGroupName = groupNameEditText.getText().toString();
		FriendsDBHelper helper = new FriendsDBHelper(this);
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(FriendsDB.GROUP_NAME, inputGroupName);
		
		Long rs = db.insert(FriendsDB.TABLE_GROUP, null, values);
		
		if(rs==-1){
			showToast(getResources().getString(R.string.toastError));
		}else{
			showToast(getResources().getString(R.string.toastSaveComplete));
			initilizeHelpers();
		}
		db.close();
		
	}
	
	protected void showupdatedGroupName(String curName) {
		String inputGroupName = groupNameEditText.getText().toString();
		FriendsDBHelper helper = new FriendsDBHelper(this);
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(FriendsDB.GROUP_NAME,inputGroupName);
		String where = FriendsDB.GROUP_NAME + " = ('" +currentTitle + "')";
		
		int rs = db.update(FriendsDB.TABLE_GROUP, values, where, null);
		db.close();
		
		if(rs==1){
			showToast(getResources().getString(R.string.toastSaveComplete));
			initilizeHelpers();
		}else{
			showToast(getResources().getString(R.string.toastError));
		}
		
	}
	
	

	
	private void initilizeHelpers() {
		
		
		menuList = getGroupList();

		ListView01 = (ListView) findViewById(R.id.listFirst);
		HomeMenuAdapter infomenuAdapter = new HomeMenuAdapter(this,
				R.layout.row_homemenu_layout, menuList);

		ListView01.setAdapter(infomenuAdapter);

		ListView01.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				FriendsCommonItem curItem = menuList.get(position);

				if(curItem.getNewcount()>0){
					callSubGroup(curItem.get_id(), curItem.getTitle(), curItem
							.getNewcount());
				}
				
			}
		});
	}
	
	private boolean isExistGroupName(String str){
		boolean result =false;
		
		menuList = getGroupList();
		
		for(FriendsCommonItem curGroup : menuList){
			Log.v("changdoc",curGroup.getTitle()+"/"+str);
			if(str.equals(curGroup.getTitle())){
				result = true;
				break;
			}
		}
		
		return result;
	}
	private void deleteGroup(String inputGroupName) {
		
		FriendsDBHelper helper = new FriendsDBHelper(this);
		SQLiteDatabase db = helper.getWritableDatabase();
		
		String where = FriendsDB.GROUP_NAME + " = ('" + inputGroupName +"')";
		int rs = db.delete(FriendsDB.TABLE_GROUP, where, null);
		
		
		if(rs<1){
			showToast(this.getResources().getString(R.string.toastError));
		}else if(rs==1){
			showToast(this.getResources().getString(R.string.toastSaveComplete));
		}
		db.close();
		groupActivityChangeToEdit();
	}
	
	private void confirmDelete(final String inputGroupName){
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle(getResources().getString(R.string.warningdelete));
		ad.setPositiveButton("OK",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				deleteGroup(inputGroupName);
			}
		});
		ad.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		ad.create().show();
	}
	
	

	private ArrayList<FriendsCommonItem> getGroupList() {
		if (manager == null)
			manager = new FriendsGroupManager(this, getContentResolver());

		return manager.getGroupList();
	}
	protected void callSubGroup(String action, String groupname, int size) {
		Intent i = new Intent(this, SubGroup.class).setAction(action).putExtra(
				"head", groupname).putExtra("size", size);
		startActivity(i);
	}

	protected void onResume() {
		super.onResume();
		initilizeHelpers();
	}
	
	private void showToast(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
	private void showToastLong(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}
}
